import 'dart:io';

import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ohos/app/common/global.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';

import 'components/crop_page.dart';
import 'eight_logic.dart';
import 'eight_state.dart';

class EightPage extends StatelessWidget {
  EightPage({Key? key}) : super(key: key);

  final EightLogic logic = Get.put(EightLogic());
  final EightState state = Get.find<EightLogic>().state;


  @override
  Widget build(BuildContext context) {

    return GetBuilder<EightLogic>(builder: (_){
      return  Scaffold(
        appBar: !kIsWeb ? AppBar(title: Text('图片剪裁')) : null,
        body: Column(
          mainAxisSize: MainAxisSize.max,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(child: _body()),
          ],
        ),
      );
    });

  }

  Widget _body() {
    if (state.croppedFile != null || state.pickedFile != null) {
      return _imageCard();
    } else {
      return _uploaderCard();
    }
  }

  Widget _imageCard() {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Padding(
            padding:
            const EdgeInsets.symmetric(horizontal: kIsWeb ? 24.0 : 16.0),
            child: Card(
              elevation: 4.0,
              child: Padding(
                padding: const EdgeInsets.all(kIsWeb ? 24.0 : 16.0),
                child: _image(),
              ),
            ),
          ),
          const SizedBox(height: 24.0),
          _menu(),
        ],
      ),
    );
  }

  Widget _image() {
    final screenWidth = MediaQuery.of(Get.context!)
        .size
        .width;
    final screenHeight = MediaQuery
        .of(Get.context!)
        .size
        .height;
    if (state.croppedFile != null) {
      final path = state.croppedFile!;
      return ConstrainedBox(
        constraints: BoxConstraints(
          maxWidth: 0.8 * screenWidth,
          maxHeight: 0.7 * screenHeight,
        ),
        child: kIsWeb ? Image.network(path) : Image.file(File(path)),
      );
    } else if (state.pickedFile != null) {
      final path = state.pickedFile!;
      return ConstrainedBox(
        constraints: BoxConstraints(
          maxWidth: 0.8 * screenWidth,
          maxHeight: 0.7 * screenHeight,
        ),
        child: kIsWeb ? Image.network(path) : Image.file(File(path)),
      );
    } else {
      return const SizedBox.shrink();
    }
  }

  Widget _menu() {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        FloatingActionButton(
          onPressed: () {
            _clear();
          },
          backgroundColor: Colors.redAccent,
          tooltip: 'Delete',
          child: const Icon(Icons.delete),
        ),
        if (state.croppedFile == null)
          Padding(
            padding: const EdgeInsets.only(left: 32.0),
            child: FloatingActionButton(
              onPressed: () {
                _cropImage();
              },
              backgroundColor: const Color(0xFFBC764A),
              tooltip: 'Crop',
              child: const Icon(Icons.crop),
            ),
          )
      ],
    );
  }

  Widget _uploaderCard() {
    return Center(
      child: Card(
        elevation: 4.0,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16.0),
        ),
        child: SizedBox(
          width: kIsWeb ? 380.0 : 320.0,
          height: 300.0,
          child: Column(
            mainAxisSize: MainAxisSize.max,
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: DottedBorder(
                    radius: const Radius.circular(12.0),
                    borderType: BorderType.RRect,
                    dashPattern: const [8, 4],
                    color: Theme
                        .of(Get.context!)
                        .highlightColor
                        .withOpacity(0.4),
                    child: Center(
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Icon(
                            Icons.image,
                            color: Theme
                                .of(Get.context!)
                                .highlightColor,
                            size: 80.0,
                          ),
                          const SizedBox(height: 24.0),
                          Text(
                            'Upload an image to start',
                            style: kIsWeb
                                ? Theme
                                .of(Get.context!)
                                .textTheme
                                .headlineSmall!
                                .copyWith(
                                color: Theme
                                    .of(Get.context!)
                                    .highlightColor)
                                : Theme
                                .of(Get.context!)
                                .textTheme
                                .bodyMedium!
                                .copyWith(
                                color:
                                Theme
                                    .of(Get.context!)
                                    .highlightColor),
                          )
                        ],
                      ),
                    ),
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 24.0),
                child: ElevatedButton(
                  onPressed: () {
                    _uploadImage();
                  },
                  style:
                  ElevatedButton.styleFrom(foregroundColor: Colors.white),
                  child: const Text('Upload',style: TextStyle(color: Colors.red),),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _cropImage() async {
    if (state.pickedFile != null) {
      String? croppedFile = await Navigator.push<String?>(
        Get.context!,
        MaterialPageRoute(
            builder: (context) => CropWidget(filePath: state.pickedFile!,)),
      );
      if (croppedFile != null) {
        state.croppedFile = croppedFile;
        logic.update();
      }
    }
  }

  Future<void> _uploadImage() async {
    final pickedFile =
    await ImagePicker().pickImage(source: ImageSource.gallery);
    if (pickedFile != null) {
      state.pickedFile = pickedFile.path;
      logic.update();
    }
  }


  void _clear() {
    if (state.croppedFile != null) {
      File(state.croppedFile!).delete();
    }
    state.pickedFile = null;
    state.croppedFile = null;
    logic.update();
  }

}
